let express = require('express')
let app = express()
let fs = require('fs')
let bodyParser = require('body-parser')
let multer = require('multer') // 引入文件上传模块

// 引入数据库
let mysql = require('mysql')
// 连接数据库
let connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'login'
})
connection.connect();

/* 1.创建数据库 create database login
    2.使用 use login；
    2.创建表
        create table users(
            id int primary key not null auto_increment,
            username char(32) not null,
            pswd char(32) not null,
            createTime timestamp
        )engine=innodb default charset=utf8;
    4.插入数据
        insert into users(username,pswd,createTime) values('admin','admin',now());
        insert into users(username,pswd,createTime) values('user','123456',now());
        insert into users(username,pswd,createTime) values('stu1','123456',now());
        insert into users(username,pswd,createTime) values('stu2','123456',now());
*/

app.use(multer({ dest: '/temp/' }).array('file')) // 把流形式的文件自动存放到临时文件夹temp，把文件处理为数组
app.use('/static', express.static("static"))
app.use(bodyParser.urlencoded({ extended: false }))
app.get('/', function (req, res) {
    fs.readFile('index.html', function (err, data) {
        if (err) {
            res.send(err.message)
            return
        }
        res.send(data.toString())
    })
})
app.post('/api/login', function (req, res) {
    /* let data = ''
    req.on('data', function (chunk) {
        data += chunk
    })
    req.on('end', function (chunk) {
        console.log(data)
        res.send('login ok')
    }) */
    console.log(req.body)
    let { username, pswd } = req.body
    let querystr = "select * from users where username='" + username + "' and pswd='" + pswd + "'"
    console.log(querystr)
    connection.query(querystr, function (err, result) {
        if (err) throw err;
        console.log('result', result)
        if (result.length == 0) {
            res.send('用户名或密码错误')
        } else {
            res.json({ success: true, data: result[0] })
        }
    })
})
// app.post('/api/upload', function (req, res) { // 异步不能确保接收和返回信息的准确性 建议使用aysic await
//     console.log(req.files)
//     for (let i = 0; i < req.files.length; i++) {
//         let file = req.files[i] // 获取单个上传文件
//         let path = __dirname + "/imgs/" + file.originalname // 设置文件保存位置
//         fs.readFile(file.path, function (err, data) {
//             console.log(data)
//             fs.writeFile(path, data, function (err2) { })
//         })
//     }
//     res.send('file upload ok')
// })

function uploadPromise (file, path) {
    return new Promise(function (resolve, reject) {
        fs.readFile(file.path, function (err, data) {
            if (err) {
                reject({ success: false, msg: err.message })
                return
            }
            console.log(data)
            fs.writeFile(path, data, function (err2) {
                if (err2) {
                    reject({ succss: false, msg: err2.message })
                    return
                }
                resolve({ success: true, msg: '文件上传成功' })
            })
        })
    }).then(data => data)
}
app.post('/api/upload', async function (req, res) { // 使用aysic await
    //     console.log(req.files)
    for (let i = 0; i < req.files.length; i++) {
        let file = req.files[i] // 获取单个上传文件
        let path = __dirname + "/imgs/" + file.originalname // 设置文件保存位置
        let data = await uploadPromise(file, path)
        console.log(data)
        if (!data.success) {
            res.send('upload error')
            return
        }
    }
    res.send('files upload ok')
})
app.listen(8080, function () {
    console.log('server start');
})